<template>
  <div class="admin-elder-management">
    <div class="header">
      <h2>老人信息管理</h2>
      <p class="subtitle">管理养老院所有老人的基本信息</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.name"
            placeholder="搜索老人姓名"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchParams.gender"
            placeholder="性别筛选"
            clearable
            @change="handleSearch"
          >
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchParams.healthStatus"
            placeholder="健康状况"
            clearable
            @change="handleSearch"
          >
            <el-option label="良好" value="良好" />
            <el-option label="一般" value="一般" />
            <el-option label="较差" value="较差" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchParams.elderSector"
            placeholder="区域筛选"
            clearable
            @change="handleSearch"
          >
            <el-option label="A区" value="A区" />
            <el-option label="B区" value="B区" />
            <el-option label="C区" value="C区" />
            <el-option label="D区" value="D区" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="elderList"
        v-loading="loading"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="姓名" width="100" sortable />
        <el-table-column prop="age" label="年龄" width="80" sortable />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? 'primary' : 'danger'">
              {{ row.gender === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="healthStatus" label="健康状况" width="120" />
        <el-table-column prop="elderSector" label="所在区域" width="100" />
        <el-table-column prop="bedNumber" label="床位号" width="100" />
        <el-table-column prop="caregiverName" label="负责护工" width="120" />
        <el-table-column prop="admissionDate" label="入住日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.admissionDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在院' : '已出院' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleViewDetail(row)"
            >
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDischarge(row)"
              v-if="row.status === 1"
            >
              <el-icon><Close /></el-icon>
              出院
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 老人详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="老人详细信息"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <el-descriptions :column="2" border v-if="currentElder">
        <el-descriptions-item label="姓名">{{ currentElder.name }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ currentElder.age }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag :type="currentElder.gender === 1 ? 'primary' : 'danger'">
            {{ currentElder.gender === 1 ? '男' : '女' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentElder.phone }}</el-descriptions-item>
        <el-descriptions-item label="健康状况" :span="2">{{ currentElder.healthStatus }}</el-descriptions-item>
        <el-descriptions-item label="所在区域">{{ currentElder.elderSector }}</el-descriptions-item>
        <el-descriptions-item label="床位号">{{ currentElder.bedNumber }}</el-descriptions-item>
        <el-descriptions-item label="负责护工">{{ currentElder.caregiverName }}</el-descriptions-item>
        <el-descriptions-item label="入住日期">{{ formatDate(currentElder.admissionDate) }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系人">{{ currentElder.emergencyContact }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系电话">{{ currentElder.emergencyPhone }}</el-descriptions-item>
        <el-descriptions-item label="特殊需求" :span="2">
          <el-tag v-if="currentElder.specialNeeds" type="info">{{ currentElder.specialNeeds }}</el-tag>
          <span v-else>无特殊需求</span>
        </el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ currentElder.address }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="handleCloseDetail">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑老人信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑老人信息"
      width="600px"
      :before-close="handleCloseEdit"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
        v-if="currentElder"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editForm.age" :min="60" :max="120" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="健康状况" prop="healthStatus">
          <el-input v-model="editForm.healthStatus" />
        </el-form-item>
        <el-form-item label="所在区域" prop="elderSector">
          <el-select v-model="editForm.elderSector" placeholder="请选择区域">
            <el-option label="A区" value="A区" />
            <el-option label="B区" value="B区" />
            <el-option label="C区" value="C区" />
            <el-option label="D区" value="D区" />
            <el-option label="E区" value="E区" />
            <el-option label="F区" value="F区" />
            <el-option label="G区" value="G区" />
            <el-option label="H区" value="H区" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="editForm.emergencyContact" />
        </el-form-item>
        <el-form-item label="紧急电话" prop="emergencyPhone">
          <el-input v-model="editForm.emergencyPhone" />
        </el-form-item>
        <el-form-item label="特殊需求" prop="specialNeeds">
          <el-input
            v-model="editForm.specialNeeds"
            type="textarea"
            :rows="3"
            placeholder="请输入老人的特殊需求"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseEdit">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Edit, Close } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref()
const currentElder = ref(null)

// 搜索参数
const searchParams = reactive({
  name: '',
  gender: '',
  healthStatus: '',
  elderSector: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 编辑表单
const editForm = reactive({
  name: '',
  age: null,
  gender: 1,
  phone: '',
  healthStatus: '',
  elderSector: '',
  emergencyContact: '',
  emergencyPhone: '',
  specialNeeds: ''
})

// 表单验证规则
const editRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  healthStatus: [{ required: true, message: '请输入健康状况', trigger: 'blur' }],
  elderSector: [{ required: true, message: '请选择所在区域', trigger: 'change' }]
}

// 模拟数据 - 老人列表
const elderList = ref([
  {
    elderId: 1,
    name: '张大爷',
    age: 78,
    gender: 1,
    phone: '13800138010',
    healthStatus: '高血压、糖尿病',
    elderSector: 'A区',
    bedNumber: '101-A',
    caregiverName: '张护工',
    admissionDate: '2024-01-15',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '无特殊需求',
    address: '北京市朝阳区建国路100号'
  },
  {
    elderId: 2,
    name: '李大妈',
    age: 82,
    gender: 0,
    phone: '13800138011',
    healthStatus: '关节炎、骨质疏松',
    elderSector: 'A区',
    bedNumber: '102-A',
    caregiverName: '张护工',
    admissionDate: '2024-02-20',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '行动不便，需要协助',
    address: '北京市海淀区中关村大街200号'
  },
  {
    elderId: 3,
    name: '王爷爷',
    age: 85,
    gender: 1,
    phone: '13800138012',
    healthStatus: '冠心病、高血压',
    elderSector: 'B区',
    bedNumber: '103-A',
    caregiverName: '张护工',
    admissionDate: '2024-03-10',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '需要定期服药',
    address: '北京市西城区金融街300号'
  },
  {
    elderId: 4,
    name: '赵奶奶',
    age: 79,
    gender: 0,
    phone: '13800138013',
    healthStatus: '糖尿病、白内障',
    elderSector: 'B区',
    bedNumber: '103-B',
    caregiverName: '李护工',
    admissionDate: '2024-04-05',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '视力较差',
    address: '北京市东城区王府井大街400号'
  },
  {
    elderId: 5,
    name: '刘大爷',
    age: 76,
    gender: 1,
    phone: '13800138014',
    healthStatus: '慢性支气管炎',
    elderSector: 'C区',
    bedNumber: '104-A',
    caregiverName: '李护工',
    admissionDate: '2024-05-12',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '呼吸系统问题',
    address: '北京市丰台区方庄路500号'
  },
  {
    elderId: 6,
    name: '陈大妈',
    age: 81,
    gender: 0,
    phone: '13800138015',
    healthStatus: '高血压、高血脂',
    elderSector: 'C区',
    bedNumber: '104-B',
    caregiverName: '李护工',
    admissionDate: '2024-06-18',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '需要低盐饮食',
    address: '北京市石景山区古城路600号'
  },
  {
    elderId: 7,
    name: '杨爷爷',
    age: 83,
    gender: 1,
    phone: '13800138016',
    healthStatus: '帕金森综合征',
    elderSector: 'D区',
    bedNumber: '105-A',
    caregiverName: '王护工',
    admissionDate: '2024-07-22',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '行动迟缓',
    address: '北京市通州区新华大街700号'
  },
  {
    elderId: 8,
    name: '黄奶奶',
    age: 77,
    gender: 0,
    phone: '13800138017',
    healthStatus: '骨质疏松、关节炎',
    elderSector: 'D区',
    bedNumber: '105-B',
    caregiverName: '王护工',
    admissionDate: '2024-08-08',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '需要助行器',
    address: '北京市大兴区黄村路800号'
  },
  {
    elderId: 9,
    name: '周大爷',
    age: 80,
    gender: 1,
    phone: '13800138018',
    healthStatus: '高血压、心脏病',
    elderSector: 'E区',
    bedNumber: '105-C',
    caregiverName: '王护工',
    admissionDate: '2024-09-14',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '心脏功能较弱',
    address: '北京市昌平区回龙观900号'
  },
  {
    elderId: 10,
    name: '吴大妈',
    age: 84,
    gender: 0,
    phone: '13800138019',
    healthStatus: '糖尿病、高血压',
    elderSector: 'E区',
    bedNumber: '201-A',
    caregiverName: '赵护工',
    admissionDate: '2024-10-01',
    status: 1,
    emergencyContact: '家属',
    emergencyPhone: '13800138000',
    specialNeeds: '需要胰岛素治疗',
    address: '北京市顺义区机场路1000号'
  }
])

// 初始化分页总数
pagination.total = elderList.value.length

// 方法定义
const handleSearch = () => {
  loading.value = true
  // 模拟搜索延迟
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 500)
}

const handleReset = () => {
  searchParams.name = ''
  searchParams.gender = ''
  searchParams.healthStatus = ''
  searchParams.elderSector = ''
  handleSearch()
}

const handleSortChange = (sort) => {
  console.log('排序变化:', sort)
  // 这里可以实现排序逻辑
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  handleSearch()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  handleSearch()
}

const handleViewDetail = (elder) => {
  currentElder.value = elder
  detailDialogVisible.value = true
}

const handleEdit = (elder) => {
  currentElder.value = elder
  // 填充编辑表单
  Object.assign(editForm, {
    name: elder.name,
    age: elder.age,
    gender: elder.gender,
    phone: elder.phone,
    healthStatus: elder.healthStatus,
    elderSector: elder.elderSector,
    emergencyContact: elder.emergencyContact,
    emergencyPhone: elder.emergencyPhone,
    specialNeeds: elder.specialNeeds
  })
  editDialogVisible.value = true
}

const handleDischarge = async (elder) => {
  try {
    await ElMessageBox.confirm(
      `确定要为${elder.name}办理出院吗？`,
      '确认出院',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟出院操作
    loading.value = true
    setTimeout(() => {
      elder.status = 0
      loading.value = false
      ElMessage.success(`${elder.name}出院成功`)
    }, 1000)
  } catch {
    ElMessage.info('已取消出院操作')
  }
}

const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentElder.value = null
}

const handleCloseEdit = () => {
  editDialogVisible.value = false
  currentElder.value = null
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    // 模拟保存操作
    setTimeout(() => {
      // 更新老人信息
      if (currentElder.value) {
        Object.assign(currentElder.value, editForm)
      }
      saving.value = false
      editDialogVisible.value = false
      ElMessage.success('老人信息更新成功')
    }, 1000)
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入')
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.admin-elder-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.subtitle {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-section {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style>
